<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Live\ServerAPIController;
use App\Http\Controllers\QrCodeController;
use App\Models\VideoLiveVote;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 视频直播管理
 */
class VideoLiveController extends CommonController
{
    protected $model;
    protected $validate;
    protected $serverAPIObj;

    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\VideoLive();
        $this->validate = new  \App\Validate\VideoLiveValidate();

        $this->serverAPIObj = new ServerAPIController();
    }

    /**
     * 列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param is_play string 是否发布   1 已发布  2 未发布
     * @param keywords string 搜索关键词
     * @param start_time datetime 活动开始时间    数据格式  年月日
     * @param end_time datetime 活动结束时间
     * @param create_start_time datetime 活动创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 活动创建结束时间
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $create_start_time = $this->request->create_start_time;
        $create_end_time = $this->request->create_end_time;
        $is_play = $this->request->is_play;

        $res = $this->model->lists(null, $keywords, $is_play, $start_time, $end_time, $create_start_time, $create_end_time, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
            $res['data'][$key]['status'] = $this->model->getVideoLiveStatus($val);
            $res['data'][$key]['size'] = format_bytes($val['size']);
            $res['data'][$key]['total_time'] = format_bytes(substr($val['total_time'], 0, 10));
            //  $res['data'][$key]['manage_name'] = Manage::getManageNameByManageId($val['manage_id']);

            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
        }

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 活动id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        $res->size = format_bytes($res->size);
        $res->total_time = format_bytes(substr($res->second_to_time, 0, 10));
        $videoLiveVoteModel = new VideoLiveVote();
        $res->vote_num = $videoLiveVoteModel->where('act_id', $res['id'])->count(); //点赞量

        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param title string 活动名称
     * @param img string 活动封面
     * @param host_handle int 主办单位
     * @param tel int 咨询电话
     * @param address int 地址
     * @param start_time int 直播开始时间
     * @param end_time string  直播结束时间
     * @param intro int 简介
     * @param is_play 是否发布 1.发布 2.未发布    默认1
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if (mb_strlen($this->request->address) > 45) {
            return $this->returnApi(202, "地址最多45个字！");
        }
        $is_exists = $this->model->nameIsExists($this->request->title, 'title');
        if ($is_exists) {
            return $this->returnApi(202, "该直播名称已存在");
        }
        //生成二维码
        $qrCodeObj = new QrCodeController();
        $qr_code = $qrCodeObj->getQrCode('video_live');
        if ($qr_code === false) {
            Log::error("视频直播二维码生成失败,请手动生成");
            return $this->returnApi(202, "二维码生成失败");
        }
        $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pMob/videoLive/index?from=readshare_activity&token=' . $qr_code; //直播活动二维码的链接  扫码跳转直播活动二维码
        $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1, [0, 0, 0], 'L'); //减小容错，让二维码更简单

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'title' => $this->request->title,
                'img' => $this->request->img ? $this->request->img : 'default/default_video_live_img.png',
                'host_handle' => $this->request->host_handle,
                'tel' => $this->request->tel,
                'address' => $this->request->address,
                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'video_num' => $this->request->video_num,
                'intro' => $this->request->intro,
                'is_play' => $this->request->is_play,
                'qr_code' => $qr_code,
                'qr_url' => $qr_url,
                'manage_id' => request()->manage_id,
            ];
            $this->model->add($data);

            //创建直播推流地址、设置录制功能
            $channel_name = $this->request->title . '-' . date('YmdHis');
            $result = $this->serverAPIObj->channelCreate($channel_name);
            if ($result['code'] === 200) {
                $cid = $result['ret']['cid'];
                //创建成功
                //设置频道为录制状态(设置录制信息)
                $result = $this->serverAPIObj->setChannelTranscribeInfo($cid, 1, 0, 30); //30分钟一段视频
                if ($result['code'] !== 200) {
                    throw new Exception('配置视频录制失败');
                }

                //获取直播推流地址
                $plug_flow_addres = $this->serverAPIObj->channelRefreshAddr($cid);
                if ($plug_flow_addres['code'] !== 200) {
                    throw new Exception($result['msg']); //'直播推流地址获取失败'
                }
                //修改之前的数据
                $this->model->where('id', $this->model->id)->update([
                    'cid' => $cid,
                    'channel_name' => $channel_name,
                    'http_pull_url' => $plug_flow_addres['ret']['httpPullUrl'],
                    'hls_pull_url' => $plug_flow_addres['ret']['hlsPullUrl'],
                    'push_url' => $plug_flow_addres['ret']['pushUrl'],
                    'rtmp_pull_url' => $plug_flow_addres['ret']['rtmpPullUrl'],
                ]);
            } else {
                throw new Exception('创建直播失败');
            }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }



    /**
     * 修改
     * @param id string 活动id
     * @param title string 活动名称
     * @param img string 活动封面
     * @param host_handle int 主办单位
     * @param tel int 咨询电话
     * @param address int 地址
     * @param start_time int 直播开始时间
     * @param end_time string  直播结束时间
     * @param intro int 简介
     * @param is_play 是否发布 1.发布 2.未发布    默认1
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if (mb_strlen($this->request->address) > 45) {
            return $this->returnApi(202, "地址最多45个字！");
        }
        $id = $this->request->id;
        $res = $this->model->where('id', $id)->where('is_del', 1)->first();

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        if ($res->status == 3) {
            return $this->returnApi(201, "直播已结束，不允许修改！");
        }

        if ($res->is_play == 1) {
            return $this->returnApi(201, "请先撤销，在进行修改！");
        }

        $is_exists = $this->model->nameIsExists($this->request->title, 'title', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "该直播名称已存在");
        }
        $old_img = $res->img;

        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'id' => $this->request->id,
                'title' => $this->request->title,
                'img' => $this->request->img ? $this->request->img : 'default/default_video_live_img.png',
                'host_handle' => $this->request->host_handle,
                'tel' => $this->request->tel,
                'address' => $this->request->address,
                'start_time' => $this->request->start_time,
                'end_time' => $this->request->end_time,
                'video_num' => $this->request->video_num,
                'intro' => $this->request->intro,
                'is_play' => $this->request->is_play,
            ];

            if (empty($res['qr_url'])) {
                //生成二维码
                $qrCodeObj = new QrCodeController();
                if (empty($res['qr_code'])) {
                    $qr_code = $qrCodeObj->getQrCode('video_live');
                    if ($qr_code === false) {
                        Log::error("视频直播二维码生成失败,请手动生成");
                        throw new Exception("二维码生成失败");
                    }
                } else {
                    $qr_code = $res['qr_code'];
                }
                //生成二维码
                $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pMob/videoLive/index?from=readshare_activity&token=' . $qr_code; //直播活动二维码的链接  扫码跳转直播活动二维码
                $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1, [0, 0, 0], 'L'); //减小容错，让二维码更简单
                $data['qr_url'] = $qr_url;
                $data['qr_code'] = $qr_code;
            }

            $this->model->change($data);

            //删除旧资源
            if ($old_img != $this->request->img && $old_img != 'default/default_video_live_img.png') {
                $this->deleteFile($old_img);
            }
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "修改失败" . $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 活动id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->detail($this->request->id, null, null);

        if (empty($res)) {
            return $this->returnApi(201, "参数传递错误");
        }
        //  if ($res['start_time'] < date('Y-m-d H:i:s') || $res['status'] != 1) {
        if (!empty($res['video_num'])) {
            return $this->returnApi(202, "当前直播已存在资源，不允许删除");
        }
        if ($res['status'] == 2) {
            return $this->returnApi(202, "此直播正在直播中，不允许删除");
        }

        DB::beginTransaction();
        try {
            $this->model->del($this->request->id);

            //禁止推流地址直播
            $result = $this->serverAPIObj->channelForbid($res['cid']);
            if ($result['code'] !== 200) {
                throw new Exception($result['msg']); //'直播推流地址获取失败'
            }
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "删除成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "删除失败" . $e->getMessage());
        }
    }

    /**
     * 修改直播状态
     * @param id int 活动id
     * @param status int 2 直播中（未开始的活动，才能设置）（弃用） 3 已结束（直播中的活动，才能设置）
     */
    public function changeLiveStatus()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change_live_status')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->detail($this->request->id, null, null);

        if (empty($res)) {
            return $this->returnApi(201, "参数传递错误");
        }
        // if ($res['status'] == 1 && $this->request->status == 3) {
        //     return $this->returnApi(201, "不能设置为此状态");
        // }
        if ($res['status'] == 3 && $this->request->status == 2) {
            return $this->returnApi(201, "不能设置为此状态");
        }

        DB::beginTransaction();
        try {
            $res->status = $this->request->status;
            $res->save();

            if ($this->request->status == 3) {
                $channelInfo = $this->serverAPIObj->channelStats($res['cid']);
                if ($channelInfo && ($channelInfo['ret']['status'] == 1 || $channelInfo['ret']['status'] == 3)) {
                    throw new Exception('直播软件正在直播中，请先关闭');
                }
                //禁止推流地址直播
                $result = $this->serverAPIObj->channelForbid($res['cid']);
                if ($result['code'] !== 200) {
                    throw new Exception($result['msg']); //'直播推流地址获取失败'
                }
            }

            DB::commit();
            return $this->returnApi(200, '设置成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 撤销 和发布
     * @param id int 活动id
     * @param is_play int 发布   1 发布  2 撤销
     */
    public function cancelAndRelease()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_and_release')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            list($code, $msg) = $this->model->resumeAndCancel($this->request->id, 'is_play', $this->request->is_play);

            $is_play = $this->request->is_play == 1 ? '发布' : '撤销';

            DB::commit();
            return $this->returnApi($code, $is_play . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 设置视频录制回调地址 (此项目，必须是：)
     * @param callback_address 视频回调地址必须  http 或 https 开头
     */
    public function setVideoCallbackAddress()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('set_video_callback_address')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if (stripos($this->request->callback_address, 'live/liveVideoCallback/getVideo') === false) {
            return $this->returnApi(201, '回调地址有误，请联系开发人员处理');
        }
        if (request()->manage_id != 1) {
            return $this->returnApi(201, '您无权配置此信息');
        }

        //设置视频录制回调地址
        $result = $this->serverAPIObj->setChannelTranscribeAddr($this->request->callback_address);

        if ($result['code'] !== 200) {
            return $this->returnApi(202, $result['msg']); //'直播推流地址获取失败'
        }

        return $this->returnApi(200, '配置成功', true);
    }
    /**
     * 获取视频录制回调地址
     */
    public function getVideoCallbackAddress()
    {
        //获取视频录制回调地址
        $result = $this->serverAPIObj->getchannelTranscribeAddr();

        if ($result['code'] !== 200) {
            return $this->returnApi(202, $result['msg']); //'直播推流地址获取失败'
        }

        return $this->returnApi(200, '配置成功', true, ['callback_address' => $result['ret']['callbackUrl'], 'create_time' => $result['ret']['lastUpdateTime']]);
    }

    /**
     * 设置频道状态变化回调地址 (此项目，必须是：)
     * @param callback_address 视频回调地址必须  http 或 https 开头
     */
    public function setChannelTranscribeAddrByState()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('set_channel_transcribe_addr_by_state')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if (stripos($this->request->callback_address, 'live/liveVideoCallback/channelStatus') === false) {
            return $this->returnApi(201, '回调地址有误，请联系开发人员处理');
        }
        if (request()->manage_id != 1) {
            return $this->returnApi(201, '您无权配置此信息');
        }

        //设置视频录制回调地址
        $result = $this->serverAPIObj->setChannelTranscribeAddrByState($this->request->callback_address);

        if ($result['code'] !== 200) {
            return $this->returnApi(202, $result['msg']); //'直播推流地址获取失败'
        }

        return $this->returnApi(200, '配置成功', true);
    }

    /**
     * 获取视频录制回调地址
     */
    public function getChannelTranscribeAddrByState()
    {
        //获取视频录制回调地址
        $result = $this->serverAPIObj->getChannelTranscribeAddrByState();

        if ($result['code'] !== 200) {
            return $this->returnApi(202, $result['msg']); //'直播推流地址获取失败'
        }

        return $this->returnApi(200, '配置成功', true, ['callback_address' => $result['ret']['callbackUrl'], 'create_time' => $result['ret']['lastUpdateTime']]);
    }
}
